package com.example.demo.jpa.customer.dao;

import com.example.demo.jpa.config.exception.CustomException;
import com.example.demo.jpa.config.exception.ExceptionResp;
import com.example.demo.jpa.customer.constants.Sex;
import com.example.demo.jpa.customer.domain.Customer;
import com.example.demo.jpa.customer.dto.CustomerCommand;
import com.example.demo.jpa.customer.dto.CustomerDTO;
import com.example.demo.jpa.customer.repo.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

import static java.util.Objects.isNull;

@Component
public class CustomerDAO {

    @Autowired
    CustomerRepository customerRepository;

    public CustomerDTO findCustomerByID(long id){
        Customer domain = customerRepository.findById(id);
        if (isNull(domain)){
            throw new CustomException(ExceptionResp.CUSTOM_NOT_FOUND,"CustomerNotFound");
        }
        CustomerDTO dto = new CustomerDTO(domain.getId(), domain.getFirstName(), domain.getLastName());
        dto.setSex(Sex.getSexByCode(domain.getSex()).name());
        return dto;
    }
    @Transactional
    public CustomerDTO  createCustomer(CustomerCommand customerCommand){
        Customer customer=new Customer(customerCommand.getFirstName(),customerCommand.getLastName(),customerCommand.getSex());
        Customer tmp=customerRepository.save(customer);
        CustomerDTO dto = new CustomerDTO(tmp.getId(), tmp.getFirstName(), tmp.getLastName());
        dto.setSex(Sex.getSexByCode(tmp.getSex()).name());
        return dto;
    }
    @Transactional
    public CustomerDTO updateCustomer(long id,CustomerCommand customerCommand){
        Customer c = customerRepository.findById(id);

        if(isNull(c)){
            throw new RuntimeException("Customer not found");
        }

        if(customerCommand.getLastName() != null){
            c.setLastName(customerCommand.getLastName());
        }
        if(customerCommand.getFirstName() != null){
            c.setFirstName(customerCommand.getFirstName());
        }
        Customer t = customerRepository.save(c);
        CustomerDTO dto = new CustomerDTO(t.getId(),t.getFirstName(),t.getLastName());
        dto.setSex(Sex.getSexByCode(t.getSex()).name());
        return dto;

    }

    @Transactional
    public void deleteCustomerById(Long id) {
        Optional<Customer> c = customerRepository.findById(id);

        if(c.isEmpty()){
            throw new RuntimeException("Customer not found");
        }else {
            customerRepository.deleteCustomerById(id);
        }

    }


}
